//
//  NetWorkViewModel.m
//  MVVM+RAC
//
//  Created by bopeng on 16/5/13.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "NetWorkViewModel.h"
#import "NetWorkModel.h"
#import <AFNetworking/AFNetworking.h>
#import <SVProgressHUD/SVProgressHUD.h>

@implementation NetWorkViewModel

- (instancetype)init {
    if (self = [super init]) {
        [self initBind];
    }
    return self;
}

- (void)initBind {
    _requestCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        RACSignal *requestSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"q"] = @"基础";
            
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
            [SVProgressHUD showWithStatus:@"正在加载..."];
            
            [[AFHTTPRequestOperationManager manager] GET:@"https://api.douban.com/v2/book/search" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [SVProgressHUD showSuccessWithStatus:@"请求成功"];
                // 请求成功
                [subscriber sendNext:responseObject];
                [subscriber sendCompleted];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
               // 请求失败调用
                [SVProgressHUD showErrorWithStatus:@"请求失败"];
                [subscriber sendNext:error];
                [subscriber sendCompleted];
            }];
                        
            return nil;
        }];
        
        return [requestSignal map:^id(id value) {
            
            // 如果请求出错
            if (![value isKindOfClass:[NSDictionary class]]){
                return 0;
            }
            
            NSDictionary *dict = (NSDictionary *)value;
            NSMutableArray *dicArr = dict[@"books"];
            
            // 字典转模型
            NSArray *modelArr = [[dicArr.rac_sequence map:^id(id value) {
                return [NetWorkModel modelWithDic:value];
            }] array];
            
            return modelArr;
        }];
    }];
    

    
}

@end
